package com.kingyun.gpsinspection.purificationservice.services.som.innerservice.impl;

import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.DynamicMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.InfoflowCommentMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.InfoflowMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.InfoflowUserMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutEmployeeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutOrganizationService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.InfoflowService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomFileService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomUserService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomWorkOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * Created by yangcs on 2017/5/3.
 */
public class InfoflowServiceImpl implements InfoflowService {
    private static Logger logger = LoggerFactory.getLogger(InfoflowServiceImpl.class);

    @Autowired
    private InfoflowMapper infoflowMapper;
    @Autowired
    private InfoflowCommentMapper infoflowCommentMapper;
    @Autowired
    private InfoflowUserMapper infoflowUserMapper;
    @Autowired
    private OutOrganizationService outOrganizationService;
    @Autowired
    private SomFileService somFileService;
    @Autowired
    private SomWorkOrderService workOrderService;
    @Autowired
    private OutEmployeeService outEmployeeService;
    @Autowired
    private SomUserService userService;
    @Autowired
    private DynamicMapper dynamicMapper;

    /**
     * 获取工作动态
     * @param userId
     * @param offset
     * @param limit
     * @return
     */
    @Override
    public List<Infoflow> queryList(String userId, int offset, int limit) {
        Map map = new HashMap<>();
        try {
            map.put("orgId",outOrganizationService.getUserOrgId(userId));
        } catch (Exception e) {
            logger.error("获取人员所属组织机构出错：userId="+userId);
            e.printStackTrace();
        }
        map.put("offset",offset);
        map.put("limit",limit);
        map.put("userId",userId);
        List<Infoflow> list = infoflowMapper.queryList(map);
        List<Infoflow> newList = new ArrayList<>();
        if( list != null && list.size() > 0 ){
            for ( Infoflow infoflow:list ){
                // 图片
                infoflow.setFiles(somFileService.findByBusiness(infoflow.getInfoflowId()));
                // 点赞
                infoflow.setLikeList(infoflowUserMapper.queryByInfoflowId(infoflow.getInfoflowId()));
                // 评论
                infoflow.setComments(infoflowCommentMapper.queryByInfoflowId(infoflow.getInfoflowId()));
                newList.add(infoflow);
            }
        }
        return newList;
    }

    /**
     * 添加评论
     * @param userId
     * @param content
     * @param infoflowCommentId
     * @param infoflowId
     * @return
     */
    @Override
    public InfoflowComment addComment(String userId, String content, String infoflowCommentId, String infoflowId) {
        InfoflowComment infoflowComment = new InfoflowComment();
        infoflowComment.setInfoflowCommentId(UniqueUtil.uuid());
        infoflowComment.setInfoflowId(infoflowId);
        infoflowComment.setTargetCommentId(infoflowCommentId);
        infoflowComment.setContent(content);
        infoflowComment.setCreateUserId(userId);
        infoflowComment.setCreateTimeStr(DateUtil.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        int result = infoflowCommentMapper.insert(infoflowComment);
        if( result < 1 ){
            return null;
        }else{
            return infoflowComment;
        }
    }

    /**
     * 点赞
     * @param userId
     * @param infoflowId
     * @return
     */
    @Override
    public InfoflowUser addPraise(String userId, String infoflowId) {
        InfoflowUser infoflowUser = new InfoflowUser();
        infoflowUser.setUserId(userId);
        infoflowUser.setInfoflowId(infoflowId);
        int result = infoflowUserMapper.insert(infoflowUser);
        if( result < 1 ){
            return null;
        }else{
            return infoflowUser;
        }
    }

    /**
     * 添加动态
     * @param infoflow
     * @return
     */
    @Override
    public Infoflow addInfoflow(Infoflow infoflow) {
        infoflow.setInfoflowId(UniqueUtil.uuid());
        int result = infoflowMapper.insert(infoflow);
        if( result < 1 ){
            return null;
        }else{
            // 插入文件信息
            List<File> files = infoflow.getFiles();
            // 不为空则循环数据
            if( files != null && files.size() > 0 ){
                for ( File f : files ){
                    f.setBusinessId(infoflow.getInfoflowId());
                    f.setFileId(UniqueUtil.uuid());
                    somFileService.insert(f);
                }
            }
            return infoflow;
        }
    }

    /**
     * 完成工单是 添加工作动态
     * @param workOrderId
     * @param finishUser
     * @param finishTime
     * @param userId
     * @return
     */
    @Override
    public int addInfoflowByFinishOrder(String workOrderId, String finishUser, long finishTime, String userId,List<File> files) {
        WorkOrder order = workOrderService.queryById(workOrderId);
        Infoflow infoflow = new Infoflow();
        infoflow.setType((short)1);
        infoflow.setShortText(order.getWorkOrderName());
        infoflow.setCreateUserId(userId);
        infoflow.setBusinessId(workOrderId);
        infoflow.setOrgId( outEmployeeService.findById(userId).getOrgId() );
        infoflow.setLongText( userService.queryUserNamesByIds( Arrays.asList(finishUser.split(",")) ) +"于" +
                DateUtil.DateToString(new Date(finishTime),"yyyy-MM-dd HH:mm") + "执行了工单："+order.getWorkOrderName());
        infoflow.setFiles(files);
        infoflow = addInfoflow(infoflow);
        if( infoflow == null ){
            return 0;
        }else{
            return 1;
        }
    }

    /**
     * web端获取工作动态
     * @param userId
     * @param offset
     * @param limit
     * @return
     */
    @Override
    public List<Dynamic> queryByParams(String userId, int limit, int offset) {
        Dynamic dynamic = new Dynamic();
        try {
            dynamic.setOrgId(outOrganizationService.getUserOrgId(userId));
        } catch (Exception e) {
            logger.error("获取人员所属组织机构出错：userId="+userId);
            e.printStackTrace();
        }
        dynamic.setOffset(offset);
        if( limit == 0 ){
            limit = 5;
        }
        dynamic.setLimit(limit);
        dynamic.setOffset(offset);
        dynamic.setUserId(userId);
        List<Dynamic> list = dynamicMapper.queryByParams(dynamic);
        List<Dynamic> newList = new ArrayList<>();
        if( list != null && list.size() > 0 ){
            for( Dynamic d : list ){
                // 点赞
                d.setPraisePeople( infoflowUserMapper.queryAll(d.getDynamicId()) );
                // 图片
                d.setCarouselInner( somFileService.findByBusiness(d.getDynamicId()) );
                // 评论
                d.setComment(infoflowCommentMapper.queryByInfoflowId(d.getDynamicId()));
                newList.add(d);
            }
        }else{
            newList = list;
        }
        return newList;
    }

    /**
     * 获取评论信息
     * @param infoflowCommentId
     * @return
     */
    @Override
    public InfoflowComment queryById(String infoflowCommentId) {
        return infoflowCommentMapper.queryById(infoflowCommentId);
    }

    /**
     * 进站确认时，添加工作动态
     * @param stationIn
     */
    @Override
    public int addInfoflowByInOut(StationIn stationIn, File file) {
        List<File> files = new ArrayList<>();
        files.add(file);
        Infoflow infoflow = new Infoflow();
        infoflow.setFiles(files);
        infoflow.setType((short)1);
        infoflow.setShortText("进站确认");
        infoflow.setCreateUserId(stationIn.getCreateUserId());
        infoflow.setBusinessId(stationIn.getStationInId());
        infoflow.setOrgId( outEmployeeService.findById(stationIn.getCreateUserId()).getOrgId() );
        infoflow.setInfoflowId(UniqueUtil.uuid());
        String orgName = "井站";
        try {
            orgName = outOrganizationService.queryOrganization(infoflow.getOrgId()).getOrgName();
        } catch (Exception e) {
            logger.error("调用组织接口失败"+e.getMessage());
            e.printStackTrace();
        }
        infoflow.setLongText( userService.queryUserNamesByIds( Arrays.asList(stationIn.getCreateUserId().split(",")) ) +"等"+stationIn.getManNumb() +"人于" +
                DateUtil.DateToString(stationIn.getInTime(),"yyyy-MM-dd HH:mm") + "进入："+orgName);
        return infoflowMapper.insert(infoflow);
    }
}
